﻿using BLL.YQZS;
using Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace YQFK.api
{
    /// <summary>
    /// 疫情追溯
    /// </summary>
    public class YqzsController : ApiController
    {
        private readonly YqzsBLL _yqzsBLL;
        public YqzsController()
        {
            _yqzsBLL = new YqzsBLL();
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns>列表</returns>
        public async Task<YqzsCountModel> Get(string deptid = null, string employeeType = null)
        {
            return await _yqzsBLL.CountAsync(deptid, employeeType);
        }

        ///// <summary>
        ///// 疫情追溯详情
        ///// </summary>
        ///// <param name="id">主键</param>
        ///// <returns>详情</returns>
        //[HttpGet]
        //public async Task<YqzsModel> Get(Guid id)
        //{
        //    var model = await _yqzsBLL.GetAsync(id);
        //    if (model.Employee.EmployeeImage != null) model.Employee.EmployeeImage.Url = Url.Link("DefaultApi", new { id = model.Employee.EmployeeImage.AttachmentId, controller = "Attachment", action = "Get" });
        //    if (model.Attachments != null)
        //    {
        //        foreach (var item in model.Attachments)
        //        {
        //            item.Url = Url.Link("DefaultApi", new { id = item.AttachmentId, controller = "Attachment", action = "Get" });
        //        }
        //    }
        //    return model;
        //}

        ///// <summary>
        ///// 新增
        ///// </summary>
        ///// <param name="model">内容</param>
        ///// <returns>详情</returns>
        ///// <response code="201">新增成功</response>
        ///// <response code="500">验证失败</response>
        //public async Task<IHttpActionResult> Post([FromBody]YqzsModel model)
        //{
        //    if (!ModelState.IsValid) return BadRequest();

        //    model.YqzsId = Guid.NewGuid();
        //    foreach (var item in model.Tracks)
        //    {
        //        item.TrackId = Guid.NewGuid();
        //    }

        //    await _yqzsBLL.CreateAsync(model);
        //    return Created(nameof(Get), model);
        //}


        /// <summary>
        /// 编辑疫情追溯
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="json">内容</param>
        /// <returns></returns>
        /// <response code="200">编辑成功</response>
        /// <response code="400">如果找不到</response>
        /// <response code="500">验证失败</response>
        public async Task<IHttpActionResult> Put()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string filepath = Path.Combine(AppContext.BaseDirectory, "App_Data");
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);

            var provider = new MultipartFormDataStreamProvider(filepath);
            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                var json = provider.FormData["json"];
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<YqzsModel>(json);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var attachmentModel = new AttachmentModel() { AttachmentId = Guid.NewGuid(), FileName = file.Headers.ContentDisposition.FileName.Trim(new char[] { '"' }), MediaType = file.Headers.ContentType.MediaType };
                    var fileinfo = new FileInfo(file.LocalFileName);
                    using (var fs = fileinfo.OpenRead())
                    {
                        attachmentModel.FileStream = new byte[fs.Length];
                        fs.Read(attachmentModel.FileStream, 0, attachmentModel.FileStream.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    if (model.Attachments == null)
                        model.Attachments = new List<AttachmentModel>();
                    model.Attachments.Add(attachmentModel);

                    attachmentModel.Extension = attachmentModel.FileName.Substring(attachmentModel.FileName.LastIndexOf('.'));
                    File.Delete(file.LocalFileName);
                }

                if (!ModelState.IsValid) return BadRequest();

                foreach (var item in model.Tracks)
                {
                    if (item.TrackId == Guid.Empty)
                        item.TrackId = Guid.NewGuid();
                }
                await _yqzsBLL.UpdateAsync(model);

                return Ok();
            }
            catch (System.Exception e)
            {
                return InternalServerError(e);
            }

            //if (!ModelState.IsValid) return BadRequest();

            //foreach (var item in model.Tracks)
            //{
            //    if (item.TrackId == Guid.Empty) item.TrackId = Guid.NewGuid();
            //}

            //await _yqzsBLL.UpdateAsync(model);
            //return Ok();
        }


        ///// <summary>
        ///// 删除
        ///// </summary>
        ///// <param name="id">主键</param>
        ///// <response code="200">删除成功</response>
        ///// <response code="400">如果找不到</response>
        //public async Task<IHttpActionResult> Delete(Guid id)
        //{
        //    var data = await _yqzsBLL.GetAsync(id);
        //    if (data == null) return NotFound();

        //    await _yqzsBLL.DeleteAsync(id);
        //    return Ok();
        //}
    }
}
